package com.zhangzhan.gulimallorder.listener;

import com.rabbitmq.client.Channel;
import com.zhangzhan.gulimallcommcon.tos.SeckillCreateTo;
import com.zhangzhan.gulimallorder.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

import static com.zhangzhan.gulimallcommcon.constant.orderAndWareUnLockCons.OrderCancelMqConstant.SECKILL_CREATE_ORDER_QUEUE;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/7/5 13:59
 */
@Slf4j
@Component
@RabbitListener(queues = SECKILL_CREATE_ORDER_QUEUE)
public class SeckillOrderCreateListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 秒杀创建订单
     *
     * @param seckillCreateTo
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    @Transactional
    public void seckillCreate(SeckillCreateTo seckillCreateTo, Message message, Channel channel) throws IOException {
        log.info("秒杀成功创建订单，订单号：{}，用户：{}", seckillCreateTo.getOrderSn(), seckillCreateTo.getMemberTo().getUsername());
        String res = orderService.seckillCreate(seckillCreateTo);
        if (res.equals("success")) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("秒杀订单创建成功，订单号：{}，用户：{}", seckillCreateTo.getOrderSn(), seckillCreateTo.getMemberTo().getUsername());
        } else {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
